

let Player = cc.Class({
    extends: cc.EventTarget,

    properties: {
        dataKey: 'user',
        configKey: 'userConfig',
        gameKey: 'userGame',

        // config
        enableSoundEffect: {
            get() {
                return this.config.sound == true;
            },
            set(val) {
                this.config.sound = val;
                this.saveConfig();
            }
        },

        // data
        hasDailyPrize: {
            get() {
                if (this.data.dailyPrizeTime) {
                    let date = new Date(this.data.dailyPrizeTime),
                        nowDate = new Date();
                    if (date.toLocaleDateString() == nowDate.toLocaleDateString())
                        return false;
                }

                return true;
            },
            set(val) {
                game.player.dailyPrizeTime = val ? 0 : cc.sys.now();
            }
        }
    },

    ctor() {
        this.data = this.getStorage(this.dataKey) || {
            newbie: true,
            dailyPrizeTime: 0,

            score: 0,
            itemCount: 0,
            shareCount: 0
        };

        this.config = this.getStorage(this.configKey) || {
            sound: true
        };

        this.gameData = this.getStorage(this.gameKey);
    },

    saveData() {
        this.emit('save-data');

        this.setStorage(this.dataKey, this.data);
    },
    saveConfig() {
        this.setStorage(this.configKey, this.config);
    },
    saveGameData(gameData) {
        this.gameData = gameData || this.gameData;
        this.setStorage(this.gameKey, this.gameData);
    },
    removeGameData() {
        this.gameData = null;
        this.removeStorage(this.gameKey);
    },

    getStorage(key) {
        return JSON.parse( cc.sys.localStorage.getItem(key) || 'null' );
    },
    setStorage(key, data) {
        cc.sys.localStorage.setItem(key, JSON.stringify(data));
    },
    removeStorage(key) {
        cc.sys.localStorage.removeItem(key);
    }
});


let props = [
    'newbie', 'dailyPrizeTime', 'score', 'shareCount',
    {prop: 'itemCount', valueFn: value => Math.max(0, value)}
];

let dataProp = {};

for (let i = 0, prop; prop = props[i++];) {
    let valueFn;
    if (prop instanceof Object) {
        valueFn = prop.valueFn;
        prop = prop.prop;
    }

    cc.js.getset(
        Player.prototype,
        prop,
        function () {
            return this.data[prop];
        }, function (val) {
            this.data[prop] = valueFn ? valueFn.call(this, val) : val;

            this.emit('set-prop', prop);
            this.saveData();
        }
    );

    dataProp[prop] = i;
}

Player.DataProperty = cc.Enum(dataProp);
